package com.woniuxy.lrz.carlproject.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.lrz.carlproject.common.AppException;
import com.woniuxy.lrz.carlproject.controller.form.formcar.CarTypeAddOrUpdateForm;
import com.woniuxy.lrz.carlproject.controller.form.shopform.formcar.CarTypeFindForm;
import com.woniuxy.lrz.carlproject.dao.CarDetailMapper;
import com.woniuxy.lrz.carlproject.model.CarDetail;
import com.woniuxy.lrz.carlproject.model.CarType;
import com.woniuxy.lrz.carlproject.dao.CarTypeMapper;
import com.woniuxy.lrz.carlproject.service.CarTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.lrz.carlproject.service.dto.dtocar.CarTypeBrandDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * <p>
 * 汽车车型表 服务实现类
 * </p>
 *
 * @author lrz
 * @since 2022-09-28
 */
@Service
@Slf4j
public class CarTypeServiceImpl extends ServiceImpl<CarTypeMapper, CarType> implements CarTypeService {
    @Resource
    private CarTypeMapper carTypeMapper;
    @Resource
    private CarDetailMapper carDetailMapper;

    @Override
    public boolean addOrUpdateCarType(CarTypeAddOrUpdateForm carTypeAddOrUpdateForm) {
            CarType carType = BeanUtil.copyProperties(carTypeAddOrUpdateForm, CarType.class);
            //判断操作是新增还是修改
            CarType carType1 = carTypeMapper.selectOne(new QueryWrapper<CarType>().eq("car_type_name", carType.getCarTypeName()));
            if(carType.getCarTypeId()==null){
                //新增
                if(carType1!=null){
                    throw new AppException("车型重复，请重试！");
                }
                carTypeMapper.insert(carType);
            }
            //修改
            if(carType1!=null&&carType1.getCarTypeId()!=carType.getCarTypeId()){
                throw new AppException("车型重复，请重试！");
            }
            carTypeMapper.updateById(carType);

        return true;
    }

    @Override
    public boolean deleteCarType(Integer carTypeId) {
        //验证是否重复删除
        CarType carType = carTypeMapper.selectById(carTypeId);
        if(carType==null){
            throw new AppException("请勿重复删除！");
        }
        //删除
        carTypeMapper.deleteById(carTypeId);
        //删除具体型号信息
        carDetailMapper.delete(new QueryWrapper<CarDetail>().eq("car_type_id",carTypeId));
        return true;
    }

    @Override
    public Page<CarTypeBrandDto> findCarType(CarTypeFindForm carTypeFindForm) {
        Page<CarType> page=new Page<>(carTypeFindForm.getPageNum(),carTypeFindForm.getPageSize());
        Page<CarTypeBrandDto> carType = carTypeMapper.findCarType(page, carTypeFindForm);
        return carType;
    }
}
